# main.py
#!/usr/bin/env python3
"""
翁法罗斯传奇十二因子 - 主入口文件
"""

import argparse
import asyncio
import os
import sys
from pathlib import Path

# 添加项目路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from web_interface.app import run_web_app
from auto_handler.auto_train import main as auto_train_main
from utils.system_check import SystemChecker

# 导入新组件
try:
    from utils.online_model_service import OnlineModelService
    from utils.context_manager import ContextManager
    from utils.network_monitor import create_default_failover_manager
    from models.model_strategy_manager import create_default_strategy_manager
    from game_engine.game_state import FactorType
    from config.api_config import get_available_services
except ImportError as e:
    print(f"导入新组件失败: {e}")
    # 备用导入路径
    sys.path.append(str(project_root / "utils"))
    sys.path.append(str(project_root / "models"))
    sys.path.append(str(project_root / "game_engine"))
    sys.path.append(str(project_root / "config"))
    from online_model_service import OnlineModelService
    from context_manager import ContextManager
    from network_monitor import create_default_failover_manager
    from model_strategy_manager import create_default_strategy_manager
    from game_state import FactorType
    from api_config import get_available_services

def setup_argparse():
    """设置命令行参数解析"""
    parser = argparse.ArgumentParser(description="翁法罗斯传奇十二因子平台")
    
    subparsers = parser.add_subparsers(dest="command", help="可用命令")
    
    # Web界面命令
    web_parser = subparsers.add_parser("web", help="启动Web界面")
    web_parser.add_argument("--host", default="0.0.0.0", help="绑定地址")
    web_parser.add_argument("--port", type=int, default=8000, help="绑定端口")
    
    # 训练命令
    train_parser = subparsers.add_parser("train", help="启动训练")
    train_parser.add_argument("--cycles", type=int, default=100, help="训练轮回数")
    train_parser.add_argument("--episodes", type=int, default=10, help="每轮回回合数")
    train_parser.add_argument("--online-api-key", help="在线模型API密钥")
    train_parser.add_argument("--online-model", default="gpt-4", help="在线模型名称")
    
    # 检查命令
    check_parser = subparsers.add_parser("check", help="系统检查")
    
    # 生成命令
    generate_parser = subparsers.add_parser("generate", help="生成代码")
    generate_parser.add_argument("--component", required=True, help="要生成的组件")
    
    return parser

async def initialize_hybrid_ai_components(online_api_key: str = None, service_name: str = "default"):
    """初始化混合AI架构组件"""
    print("初始化混合AI架构组件...")
    
    # 初始化在线模型服务
    online_service = None
    # 如果没有指定API密钥，尝试从配置管理器获取配置
    if not online_api_key:
        # 检查是否有可用的配置服务，优先使用开源选项
        available_services = get_available_services()
        print(f"可用服务: {available_services}")
        
        # 优先选择开源/免费服务
        service_to_use = None
        for service in ["ollama", "openrouter", "anthropic", "openai"]:
            if service in available_services:
                service_to_use = service
                break
        
        if service_to_use:
            online_service = OnlineModelService(service_name=service_to_use)
            print(f"使用配置服务 '{service_to_use}' 初始化在线模型服务")
        else:
            print("未找到可用的在线模型配置，仅使用本地模型")
    else:
        # 使用提供的API密钥
        online_service = OnlineModelService(
            api_key=online_api_key,
            default_model=os.getenv("ONLINE_MODEL_NAME", "gpt-4")
        )
        print("使用提供的API密钥初始化在线模型服务")
    
    # 初始化上下文管理器
    context_manager = ContextManager()
    print("上下文管理器已初始化")
    
    # 初始化网络监控器和故障转移管理器
    network_monitor, failover_manager = create_default_failover_manager()
    print("网络监控和故障转移管理器已初始化")
    
    # 初始化模型策略管理器
    factor_types = list(FactorType)  # 获取所有因子类型
    strategy_manager = create_default_strategy_manager(factor_types, online_api_key)
    print("模型策略管理器已初始化")
    
    # 配置故障转移管理器
    if online_service:
        failover_manager.set_online_model_service(online_service)
    # 注意：这里需要在实际使用时设置本地模型服务
    # failover_manager.set_local_model_service(strategy_manager.local_model)
    
    # 启动网络监控
    await network_monitor.start_monitoring()
    print("网络监控已启动")
    
    return {
        'online_service': online_service,
        'context_manager': context_manager,
        'network_monitor': network_monitor,
        'failover_manager': failover_manager,
        'strategy_manager': strategy_manager
    }

async def main():
    """主函数"""
    parser = setup_argparse()
    args = parser.parse_args()
    
    # 系统检查
    checker = SystemChecker()
    if not checker.check_system():
        print("系统检查失败，请解决上述问题后重试")
        return
    
    if args.command == "web":
        print(f"启动Web界面: http://{args.host}:{args.port}")
        run_web_app(args.host, args.port)
        
    elif args.command == "train":
        # 初始化混合AI架构组件
        hybrid_components = await initialize_hybrid_ai_components(args.online_api_key)
        
        print(f"开始训练 - 轮回数: {args.cycles}, 每轮回合数: {args.episodes}")
        await auto_train_main(args.cycles, args.episodes, hybrid_components)
        
    elif args.command == "check":
        checker.full_system_check()
        
    elif args.command == "generate":
        print(f"生成组件: {args.component}")
        # 这里可以调用代码生成器
        
    else:
        parser.print_help()

if __name__ == "__main__":
    asyncio.run(main())
